package com.yn.pet.util;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Maps;
import com.yn.common.constant.Constants;
import com.yn.common.exception.ServiceException;
import com.yn.common.utils.http.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.Map;
import java.util.Objects;

/**
 * @ClassName: SyncUserUtil
 * @Description:
 * @Author: lxp
 * @Date: 2025/6/6 10:51
 **/
@Slf4j
public class SyncUserUtil {


    public static String shopAppId = "wxd4d56e9826a6c8eb";

    /**
     * 同步其他平台用户信息
     *
     * @param userJson
     */
    public static void syncOtherClientUser(String userJson) {
        // 调用商城进行分发新增用户
        Map<String, Object> paramsMap = Maps.newHashMap();
        paramsMap.put("userJson", userJson);
        paramsMap.put("shopAppId", shopAppId);
        paramsMap.put("secretKey", Constants.SECRET_KEY);
        log.info("同步到其他平台接口请求参数：{}", paramsMap);

        sendPost(Constants.MALL_APP_URL_UAT + "api/front/wechat/sync-user", paramsMap);
    }


    public static void sendPost(String url, Map<String, Object> paramsMap) {
        MultiValueMap<String, Object> formData = new LinkedMultiValueMap<>();
        for (Map.Entry<String, Object> entry : paramsMap.entrySet()) {
            formData.add(entry.getKey(), entry.getValue());
        }
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        // 封装成HttpEntity
        HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(formData,headers);

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
        log.info("response:" + response);
        if (response.getStatusCode() == HttpStatus.OK) {
            log.info("response:{}", response.getBody());
            String responseObject = response.getBody();
            JSONObject jsonObject = JSON.parseObject(responseObject);
            if (jsonObject != null) {
                Integer code = jsonObject.getInteger("code");
                if (Objects.equals(code, 500)) {
                    throw new ServiceException("变更异常，请联系管理员");
                }
            }
            log.info("同步响应结果：{}", jsonObject);
        }
    }
}
